package com.example.recorder;



import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;




public class HttpUtil {
    private static long HTTP_TIMEOUT=5000;
    public static void get(String url, Callback callback) {
        try {
            OkHttpClient client = new OkHttpClient.Builder().connectTimeout(HTTP_TIMEOUT, TimeUnit.MILLISECONDS)
                    .readTimeout(HTTP_TIMEOUT, TimeUnit.MILLISECONDS).build();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void post(String url, JSONObject data, Callback callback) {
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(HTTP_TIMEOUT, TimeUnit.MILLISECONDS)
                    .readTimeout(HTTP_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data.toString());
            Request request = new Request.Builder()
                    .addHeader("Connection", "close")
                    .url(url)
                    .post(body)
                    .build();
            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //...代表可变数组大小的参数
    public static void postFile(String url, File  file, Callback callback) {

        OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000, TimeUnit.MILLISECONDS)
                .readTimeout(10000, TimeUnit.MILLISECONDS)
                .writeTimeout(10000, TimeUnit.MILLISECONDS).build();


        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        //第一个参数要与Servlet中的一致
        builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));

        MultipartBody multipartBody = builder.build();

        Request request = new Request.Builder().url(url).post(multipartBody).build();

        okHttpClient.newCall(request).enqueue(callback);
    }

}
